<template>
    <view class="content">
        <view class="box">
            <view class="item">
                <view class="title">公告标题</view>
                <textarea v-model="title" placeholder="请输入标题" class="tit-t" :auto-height="true"></textarea>
            </view>
            <view class="item">
                <view class="title">公告详情</view>
                <textarea v-model="content" placeholder="请输入详情" maxlength="-1"></textarea>
            </view>
            <view class="item">
                <view class="title">公告封面</view>
                <view class="img-box" @click="chooseImg(1)">
                    <image :src="coverUrl" class="up-photo" v-if="coverUrl"></image>
                    <image src="../../static/images/up_photo.png" class="up-photo" v-else></image>
                </view>
            </view>
            <view class="item">
                <view class="title">公告配图（最多可上传9张）</view>
                <view class="img-box">
                    <view class="img-box-item" v-for="(item, index) in imgUrl" :key="index" v-if="imgUrl.length">
                        <image :src="item" class="up-img" @click="doPreview(item)"></image>
                        <view class="del-img" @click="delImg(index)">删除</view>
                    </view>
                    <image src="../../static/images/up_photo.png" class="up-img" v-if="imgUrl.length < 9" @click="chooseImg(2)"></image>
                </view>
            </view>
            <view class="item2">
                <view>是否弹出</view>
                <view class="u-flex u-row-right inp">
                    <u-switch v-model="checked" size="40" active-color="#00a0e9" @change="change"></u-switch>
                </view>
            </view>
        </view>
        <view class="btn" @click="$noMultipleClicks(doSubmit)">立即添加</view>
        
        <view class="u-p-t-80" v-show="show">
            <canvas :style="{width: cwidth,height: cheight}" canvas-id="Canvas" id="Canvas"></canvas>
        </view>
    </view>
</template>

<script>
    import { API_URL } from '@/static/js/common.js';
    export default {
        data() {
            return {
                noClick:true,//连点
                show: true,
                URL: API_URL, //上传图片用的
                coverUrl: '',
                coverId: '',
                imgUrl: [],//图片
                imgId: [],//图片id
                title: '',
                content: '',
                
                cwidth: '',//画布宽
                cheight: '',//画布高
                urls: '',
                urlsArr: [],
                data: {},
                latitude: '',
                longitude: '',
                checked: false, //是否禁用
            };
        },
        onLoad() {
            this.$getLocation((latitude,longitude) => {
                // console.log('000',latitude, longitude)
                this.latitude = latitude
                this.longitude = longitude
                this.getAppLocation()
            })
        },
        onShow() {
            
        },
        methods: {
            doSubmit() {
                if (!this.title) {
                    this.$toast('请输入标题');
                    return
                }
                if (!this.content) {
                    this.$toast('请输入详情');
                    return
                }
                if (!this.coverId) {
                    this.$toast('请上传公告封面图');
                    return
                }
                this.$ajax('notice_submit', {
                	user_token: this.$getSync('userToken'),
                    title: this.title,//标题
                    notice: this.content,//公告详情
                    image_id: this.coverId,//封面图id
                    images: this.imgId.join(','),//配图id，分割字符串
                    id: '',//编辑 公告id
                    popup: this.checked ? 1 : 2,//1弹出 2不弹出
                }).then(ret => {
                	if (ret.success == 1000) {
                		this.$toast('添加成功');
                        setTimeout(() => {
                            this.$backT()
                        }, 300)
                	} else {
                		this.$toast(ret.msg);
                	}
                });
            },
            
            // 切换禁用
            change(status) {
            	console.log(status);
                this.checked = status;
            },
            
            getAppLocation() {
                const _this = this;
                this.$amapPlugin.getRegeo({
                    location: `${_this.longitude},${_this.latitude}`,
                	success: res => {
                        console.log('周边',res)
                        _this.data = res[0].name || res[0].desc
                	},
                	fail: err => {
                		console.log('失败',err)
                	}
                });
            },
            
            // 上传图片
            chooseImg(num) {
                var _this = this;
                _this.show = true
                var context = uni.createCanvasContext('Canvas', this)
                uni.chooseImage({
                    count: 9, //默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 相机拍照 album 相册、camera 拍照
                    success: (res) => {
                        console.log('res',res)
                        if(num == 1) {
                            _this.urls = res.tempFilePaths[0]
                            _this.uploadImg(num)
                        } else if (num == 2) {
                            const tempFilePaths = res.tempFilePaths;
                            for (let i = 0; i < tempFilePaths.length; i++) {
                                _this.urls = res.tempFilePaths[i]
                                _this.uploadImg(num)
                            }
                            // uni.getImageInfo({
                            //     src: res.tempFilePaths[0],
                            //     success: (image) => {
                            //         console.log('image',image)
                            //         _this.cwidth = image.width + 'px'
                            //         _this.cheight = image.height + 'px'
                            //         setTimeout(() => {
                            //             context.width = _this.cwidth;
                            //             context.height = _this.cheight;
                            //             // 填充一个矩形 x轴 y轴
                            //             context.fillRect(0, 0, _this.cwidth, _this.cheight);
                            //             // 绘制图像到画布，将图片src放到cancas内，宽高为图片大小
                            //             context.drawImage(res.tempFilePaths[0], 0, 0, image.width, image.height)
                                        
                            //             let time = new Date()
                            //             let nowTime = time.toLocaleString()
                                        
                            //             context.beginPath();
                            //             context.setFontSize(25);
                            //             context.setFillStyle("rgba(253, 248, 79, 0.6)");
                            //             context.fillText(nowTime, 10, 35)//当前时间
                            //             context.fillText(_this.data, 10, 65)//当前定位地址
                                        
                            //             uni.showLoading({title: '上传中...',})
                            //             context.draw(false, () => {
                            //                 setTimeout(() => {
                            //                     uni.canvasToTempFilePath({
                            //                         canvasId: "Canvas",
                            //                         fileType: 'jpg' || 'png',
                            //                         success: (path) => {
                            //                             console.log('path',path)
                            //                             _this.urls = path.tempFilePath
                            //                             // _this.urlsArr.push(path.tempFilePath)
                            //                             _this.uploadImg(num)
                            //                             uni.hideLoading()
                            //                         }
                            //                     }, this)
                            //                 }, 500)
                            //             })
                            //         }, 1000)
                            //     }
                            // })
                        }
                    }
                });
            },
            // 上传
            uploadImg(num) {
                let _this = this
                // console.log(_this.urls)
                uni.uploadFile({
                    url: _this.URL + 'api/upload_image', //仅为示例，并非真实接口地址。
                    filePath: _this.urls,
                    name: 'image',
                    formData:{module: 'api'},
                    success: result => {
                        console.log(result)
                        let data = JSON.parse(result.data).detail; //后台返回的路径data.attach_uri
                        if (num == 1) {
                            _this.coverUrl = data.image
                            _this.coverId = data.image_id
                        } else {
                            _this.imgUrl.push(data.image);
                            _this.imgId.push(data.image_id);
                            _this.show = false
                        }
                    },
                    fail: err => {
                        console.log('err', err)
                    }
                });
            },
            // 预览图片
            doPreview(item) {
            	var arr = [];
            	arr.push(item);
            	uni.previewImage({
            	    urls: arr,
            	    longPressActions: {
            	        success: function(data) {
            	        },
            	        fail: function(err) {
                            console.log(err)
            	        }
            	    }
            	});
            },
            //删除
            delImg(index) {
                uni.showModal({
                    title: '提示',
                    content: '确定要删除吗？',
                    success: res => {
                        if (res.confirm) {
                            this.imgId.splice(index, 1);
                            this.imgUrl.splice(index, 1);
                        } else if (res.cancel) {
                            
                        }
                    }
                });
            },
        }
    };
</script>

<style lang="scss">
    .item2{
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .inp{
        flex: 1;
        height: 100rpx;
        text-align: right;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    page{
        background-color: #f5f5f5;
    }
    .content{
        padding: 20rpx;
    }
    .box{
        padding: 0 20rpx;
        background-color: #fff;
        border-radius: 20rpx;
    }
    .item{
        border-bottom: 2rpx solid #e6e6e6;
        padding: 30rpx 0;
    }
    .item:last-child{
        border-bottom: none;
        padding-bottom: 10rpx;
    }
    
    .title{
        padding-bottom: 15rpx;
    }
    textarea{
        width: 94%;
        padding: 20rpx;
        background-color: #fafafa;
    }
    .tit-t{
        min-height: 100rpx;
    }
    // .img-box{
    //     display: flex;
    //     flex-wrap: wrap;
    //     justify-content: flex-start;
    //     align-items: center;
    //     position: relative;
    // }
    .up-photo{
        width: 168rpx;
        height: 168rpx;
        border-radius: 15rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;
    }
    
    .img-box{
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;
    }
    .img-box-item{
        position: relative;
    }
    .del-img{
        font-size: 24rpx;
        color: #fff;
        padding: 5rpx 8rpx;
        background: rgba(0,0,0, .5);
        position: absolute;
        right: 15rpx;
        bottom: 15rpx;
    }
    .up-img{
        width: 149rpx;
        height: 145rpx;
        margin-right: 14rpx;
        margin-bottom: 14rpx;
    }
    .btn{
        font-size: 34rpx;
        color: #fff;
        text-align: center;
        background-color: #00a1e9;
        padding: 25rpx;
        border-radius: 50rpx;
        margin: 50rpx 0;
    }
    
    
    
</style>
